/* serial_read.c
 
 Read data via serial I/O
 
 This program is distributed under the GPL, version 2
 */

#include <stdio.h>
#include <unistd.h>
#include <ftdi.h>
#include "ump.h"

int main(int argc, char **argv)
{
    int f;

	// ftdi configuration
    int vid = 0x0403;
    int pid = 0x6001;
    int baudrate = 115200;
	int latencyTimer = 1;
	int bufferSize = 64;
    int interface = INTERFACE_ANY;
	
	// ftdi vars
    struct ftdi_context ftdic;
    unsigned char buf[bufferSize];

    // Init ftdi
    if (ftdi_init(&ftdic) < 0)
    {
        fprintf(stderr, "ftdi_init failed\n");
        return EXIT_FAILURE;
    }
	
    // Select first interface
    ftdi_set_interface(&ftdic, interface);
	
    // Open device
    f = ftdi_usb_open(&ftdic, vid, pid);
    if (f < 0)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(&ftdic));
        exit(-1);
    }
	
    // Set baudrate
    f = ftdi_set_baudrate(&ftdic, baudrate);
    if (f < 0)
    {
        fprintf(stderr, "unable to set baudrate: %d (%s)\n", f, ftdi_get_error_string(&ftdic));
        exit(-1);
    }
	
    // Set latency timer
    f = ftdi_set_latency_timer(&ftdic, latencyTimer);
    if (f < 0)
    {
        fprintf(stderr, "unable to set baudrate: %d (%s)\n", f, ftdi_get_error_string(&ftdic));
        exit(-1);
    }
	
	// Set read buffer
	f = ftdi_read_data_set_chunksize(&ftdic, bufferSize);
	if(f < 0)
	{
        fprintf(stderr, "unable to set chunksize: %d (%s)\n", f, ftdi_get_error_string(&ftdic));
        exit(-1);
	}
	
	// Init ump
	ump_context umpc;
	ump_init(&umpc, 10, 8);
	ump_touch touches[umpc.length / 4];
	int numTouches;
	
    // Run loop
	int i;
    while(1)
	{
		f = ftdi_read_data(&ftdic, buf, sizeof(buf));
		
		f = ump_read(&umpc, buf, sizeof(buf));
		if(f != 0) {
			fprintf(stderr, "unable to parse serial data from UMP (ump array too small?)\n");
		}
		numTouches = ump_read_touches(&umpc, touches, umpc.length / 4);
		
		// logging
		if(numTouches > 0) {
			for(i = 0; i < numTouches; i++) {
				fprintf(stdout, "	[%d]	%.2f	%.2f	%.2f", i, touches[i].x, touches[i].y, touches[i].pressure);
			}
			fprintf(stdout, "\n");
		}
		
		ump_free_touches(touches);
		
		// sleep 1ms
		usleep(1000);
		
    }
	
	ump_deinit(&umpc);
	
    ftdi_usb_close(&ftdic);
    ftdi_deinit(&ftdic);
}
